package cool.taomu.toolkit.h2

import com.google.inject.AbstractModule
import com.google.inject.Provider
import com.google.inject.name.Names
import cool.taomu.toolkit.TaomuConfigure
import cool.taomu.toolkit.platform.inter.AbsPlatform
import org.h2.tools.Server
import com.google.inject.Inject
import com.google.inject.name.Named
import com.google.inject.Key

class H2Plugin extends AbsPlatform {

    override note() {
        "H2Database 插件"
    }

    override packages() {
    }

    override module(TaomuConfigure config) {
        new AbstractModule() {
            override configure() {
                bind(Server).annotatedWith(Names.named("taomu.h2.server")).toProvider(new Provider<Server>() {

                    @Inject(optional=true)
                    @Named("taomu.h2.serverPort")
                    Integer port = 9092

                    override get() {
                        return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", String.valueOf(port)).
                            start();
                    }
                })
                bind(Server).annotatedWith(Names.named("taomu.h2.web")).toProvider(new Provider<Server>() {

                    @Inject(optional=true)
                    @Named("taomu.h2.webPort")
                    Integer port

                    override get() {
                        if (port !== null) {
                            var webServer = Server.createWebServer("-web", "-webAllowOthers", "-webPort",
                                String.valueOf(port))
                            return webServer
                        }
                        return null;
                    }
                })
            }
        }
    }

    override start() {
        this.context.executor.submit([
            var ins = this.context.getInstance(Key.get(Server, Names.named("taomu.h2.server")))
            if (ins !== null) {
                ins.start
            }
        ])

        this.context.executor.submit([
            var ins = this.context.getInstance(Key.get(Server, Names.named("taomu.h2.web")))
            if (ins !== null) {
                ins.start
            }
        ])
    }

    override init() {
    }

}
